﻿

using SDK.Core;
using SDK.SqlSugar.Configuration;
using SqlSugar;
using System.Data;

namespace SDK.SqlSugar
{

    public class SqlSugarSdkClient : ClientBase, ISqlSugarSdkClient
    {
        private readonly ISqlSugarSdkConfig _sqlSugarSdkConfig;

        public SqlSugarSdkClient(ISqlSugarSdkConfig config) : base(config)
        {
            this._sqlSugarSdkConfig = config;
        }

        public SqlSugarClient InitSqlSugarClient()
        {
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = this._sqlSugarSdkConfig.ConnectionString,
                DbType = this._sqlSugarSdkConfig.DbType,
                IsAutoCloseConnection = this._sqlSugarSdkConfig.IsAutoCloseConnection,
                InitKeyType = this._sqlSugarSdkConfig.InitKeyType,
                ConfigureExternalServices = this._sqlSugarSdkConfig.ConfigureExternalServices
            });

            if (this._sqlSugarSdkConfig.OnDiffLogEvent != null) db.Aop.OnDiffLogEvent = this._sqlSugarSdkConfig.OnDiffLogEvent;
            if (this._sqlSugarSdkConfig.OnError != null) db.Aop.OnError = this._sqlSugarSdkConfig.OnError;
            if (this._sqlSugarSdkConfig.OnLogExecuting != null) db.Aop.OnLogExecuting = this._sqlSugarSdkConfig.OnLogExecuting;
            if (this._sqlSugarSdkConfig.OnLogExecuted != null) db.Aop.OnLogExecuted = this._sqlSugarSdkConfig.OnLogExecuted;
            if (this._sqlSugarSdkConfig.OnExecutingChangeSql != null) db.Aop.OnExecutingChangeSql = this._sqlSugarSdkConfig.OnExecutingChangeSql;

            if (db.Ado.Connection.State == ConnectionState.Closed)
            {
                db.Ado.Connection.Open();
            }

            return db;
        }
    }
}
